package com.chaoxuan.uebt.activity;

import android.util.Log;
import com.chaoxuan.uebt.App;
import com.chaoxuan.uebt.utils.CacheUtils;
import com.chaoxuan.uebt.utils.ICallBack;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Timer;
import java.util.TimerTask;

public class EmptyClient extends WebSocketClient {

    String TAG="====SOCKET====";
    String token;
    Timer timer;
    TimerTask task;
    ICallBack callBack;

    public EmptyClient(URI serverURI, String token, ICallBack callBack) {
        super(serverURI);
        this.token=token;
        this.callBack=callBack;
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        Log.d(TAG,"open");
        String message="msg|||"+token;
        send(message);
        start();
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        Log.d(TAG,"closed with exit code " + code + " additional info: " + reason);
        callBack.onChange("",true);
        stop();
    }

    @Override
    public void onMessage(String message) {
        Log.d(TAG,"received message: " + message);
        callBack.onChange(message,false);
    }

    @Override
    public void onMessage(ByteBuffer message) {
        Log.d(TAG,"received ByteBuffer");
    }

    @Override
    public void onError(Exception ex) {
        Log.d(TAG,"an error occurred:" + ex);
    }

    public void start(){
        if(timer==null) {
            timer = new Timer();
        }
        if(task==null) {
            task = new TimerTask() {
                @Override
                public void run() {
                    send("time");
                    Log.d(TAG,"time");
                }
            };
            timer.schedule(task, 0, 30 * 1000);//每隔time时间段就执行一次
        }
    }

    public void stop(){
        if (timer != null) {
            timer.cancel();
            if (task != null) {
                task.cancel();  //将原任务从队列中移除
            }
        }
        close();
    }

}
